package com.example.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.example.pojo.Result;
import com.example.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class ObjectInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String url = req.getRequestURL().toString();
        System.out.println("update form master");
        log.info("拦截到请求,路径:{}", url);
        String jwt = req.getHeader("token");
        if (!StringUtils.hasLength(jwt)) {
            log.info("未找到jwt令牌,登录失败");
            Result result = Result.error("NOT_LOGIN");
            String ResultJson = JSONObject.toJSONString(result);
            resp.getWriter().write(ResultJson);
            return false;
        }
        try {
            jwtUtils.parseJwtToken(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("jwt令牌非法,登录失败");
            Result result = Result.error("NOT_LOGIN");
            String ResultJson = JSONObject.toJSONString(result);
            resp.getWriter().write(ResultJson);
            return false;
        }
        log.info("jwt令牌合法,放行");
        return true;
    }
}
